var express = require('express');
var router = express.Router();
const user = require("../sql/User");
const md5 = require("md5");

/* 登录页面 */
router.get('/', function(req, res, next) {
  res.render('login');
});

/* 登录处理 */
router.post('/handle', function(req, res, next) {
  const {employeesName, password} = req.body;
  user.find( { employeesName, password: md5(password) } ).then(data=>{
    if(data.length > 0){
      // 存储用户信息
      req.session.userData = {
        power: data[0].power,
        uId: data[0].uId,
        employeesName: data[0].employeesName,
        job: data[0].job,
        division: data[0].division,
        gender: data[0].gender,
        tel: data[0].tel,
        password: data[0].password,
        regTime: data[0].regTime,
        isLogin:1
      };
      res.redirect('/');
    }else{
      req.flash('error', '登录失败！请检查登录信息！');
      res.redirect('/login');
    }
  }).catch(code=>{
    console.error(code);
    res.send( code );
  })
});

// 退出
router.get('/exit', function(req, res, next) {
  req.session.userData = {};
  res.redirect('/login');
})

module.exports = router;
